package com.dbq.fast.business.invite;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.invite.adapter.IItemClickListener;
import com.dbq.fast.business.invite.api.InviteApi;
import com.dbq.fast.business.invite.been.InviteInfo;
import com.dbq.fast.business.invite.been.ShareIntroduce;
import com.dbq.fast.business.invite.widget.ShareWidget;
import com.dbq.fast.business.product.ui.StatusView;
import com.dbq.fast.common.base.BaseActivity;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.util.ProgressDialogUtil;
import com.dbq.fast.util.QRCodeUtils;
import com.dbq.fast.util.ShareUtil;
import com.dbq.fast.util.SystemUtil;

import java.util.concurrent.atomic.AtomicInteger;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 该类为邀请界面
 * 界面分为两部分，基本信息展示和规则信息展示
 * 布局是使用CoordinatorLayout + AppBarLayout 实现。
 * 该界面没有返回按钮，需要通过系统自带的返回键返回。
 * 点击分享按钮，弹出dialog。在dialog中的分享数据是在进入该activity时，
 * 请求接口得到的。意味着可能用户不分享，对该接口做了无用的请求。
 */
public class InviteActivity extends BaseActivity {

    @BindView(R.id.rule)
    TextView ruleTV;
    @BindView(R.id.statusView)
    StatusView statusView;
    @BindView(R.id.wx_share_content)
    TextView wxShareContentTV;
    @BindView(R.id.rate1)
    TextView rate1TV;
    @BindView(R.id.rate2)
    TextView rate2TV;
    @BindView(R.id.rate3)
    TextView rate3TV;
    @BindView(R.id.lrate1)
    TextView lrate1TV;
    @BindView(R.id.lrate2)
    TextView lrate2TV;
    @BindView(R.id.lrate3)
    TextView lrate3TV;
    @BindView(R.id.mask)
    TextView maskTV;

    private AtomicInteger isBothOK;
    private ShareWidget shareWidget;
    private InviteInfo mInviteInfo;
    private String ruleContent = "";
    private IItemClickListener iItemClickListener = new IItemClickListener() {
        @Override
        public void onItemClick(int position) {
            if (position < 2) { //分享微信好友、朋友圈
                ProgressDialogUtil.showProgress(InviteActivity.this, "", App.getContext().getString(R.string.waiting), true);
                share2WeChat(position == 0);
                YibaAnalysis.getInstance().event(App.getContext(), position == 0 ? EventConstant.INVITE_TO_WECHAT : EventConstant.INVITE_TO_WECHAT_COMMENT);
            } else if (position == 2) { //qq
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.INVITE_TO_QQ);
                ShareUtil.share2QQ(App.getContext(), mInviteInfo.link);
            } else if (position == 3) { //weibo
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.INVITE_TO_WEIBO);
                ShareUtil.share2Weibo(App.getContext(), mInviteInfo.link);
            } else { //copy link
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.INVITE_COPY_LINK);
                SystemUtil.copyToBoad(mInviteInfo.link);
                Toast.makeText(App.getContext(), R.string.tip_copy_success, Toast.LENGTH_LONG).show();
            }
            shareWidget.destory();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invate);
        ButterKnife.bind(this);

        isBothOK = new AtomicInteger(0);

        shareWidget = new ShareWidget();
        shareWidget.setItemClickListener(iItemClickListener);

        statusView.setStatus(StatusView.LOADING);
        loadData();
        statusView.setRefreshListener(() -> {
            statusView.setStatus(StatusView.LOADING);
            loadData();
        });


    }

    @OnClick({R.id.btn_share, R.id.rule})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_share:
                shareWidget.init(InviteActivity.this, maskTV);
                shareWidget.show();

                YibaAnalysis.getInstance().event(this, EventConstant.INVITE_SHARE);
                break;
            case R.id.rule:
                if (!TextUtils.isEmpty(ruleContent)) {
                    Intent intent = new Intent(InviteActivity.this, RuleActivity.class);
                    intent.putExtra("rule_content", ruleContent);
                    startActivity(intent);
                }
                YibaAnalysis.getInstance().event(this, EventConstant.INVITE_RULE);
                break;
        }
    }


    /**
     * 一次加载两个接口的数据，根据第一个接口的加载情况处理UI逻辑
     */
    private void loadData() {
        InviteApi.inviteIntroduce(new RemoteApiCallBack<ShareIntroduce>() {

            @Override
            public void onSuccess(ShareIntroduce shareIntroduce) {
                if (statusView == null) return;
                bindData(shareIntroduce);
                netOk();
            }

            @Override
            public void onFail(int status, String message) {
                if (statusView == null) return;
                netError();
            }
        });

        InviteApi.inviteShareLink(new RemoteApiCallBack<InviteInfo>() {
            @Override
            public void onFail(int status, String message) {
                if (statusView == null) return;
                netError();
            }

            @Override
            public void onSuccess(InviteInfo inviteInfo) {
                if (statusView == null) return;
                netOk();
                mInviteInfo = inviteInfo;
            }
        });
    }

    private void netError() {
        Toast.makeText(InviteActivity.this, getString(R.string.tip_retry_network_bad), Toast.LENGTH_LONG).show();
        statusView.setStatus(StatusView.NET_ERROR);
        ruleTV.setVisibility(View.GONE);
    }

    private void netOk() {
        isBothOK.getAndIncrement();
        if (isBothOK.get() == 2) {
            statusView.setStatus(StatusView.SUCCESS);
            ruleTV.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 绑定界面数据
     *
     * @param shareIntroduce
     */
    private void bindData(ShareIntroduce shareIntroduce) {
        rate1TV.setText(shareIntroduce.rate1st);
        rate2TV.setText(shareIntroduce.rate2nd);
        rate3TV.setText(shareIntroduce.rate3rd);
        lrate1TV.setText(shareIntroduce.rate1st);
        lrate2TV.setText(shareIntroduce.rate2nd);
        lrate3TV.setText(shareIntroduce.rate3rd);
        ruleContent = shareIntroduce.rule2;
    }

    private void share2WeChat(boolean isShareFriend) {
        int leftTextVal = 60;
        int topTextVal = 420;
        int leftQRCodeVal = 220;
        int topQRCodeVal = 790;
        int edgeQRCodeVal = 280;

        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度（像素）
        int height = dm.heightPixels;       // 屏幕高度（像素）
        //兼容三星手机分享页面不适配问题
//        Log.e("yc_", "brand:" + Build.BRAND +" model:"+Build.MODEL);
//        Log.e("yc_", "width:" + width + " height:" + height);
//        Log.e("yc_", "底部导航栏高度:" + getDaoHangHeight(App.getContext()));
        if (width != 1080) {
            leftTextVal = leftTextVal * 1080 / width;
            leftQRCodeVal = leftQRCodeVal * 1080 / width;
            wxShareContentTV.setTextSize(TypedValue.COMPLEX_UNIT_PT, 28 * 1080 / width);
        }
        if (height != 1920) {
            if(Build.MODEL.contains("MIX")){ // 小米全面屏适配
                height -= SystemUtil.getDaoHangHeight(App.getContext());
                height += 20;
                topTextVal = topTextVal * 1920 / height;
                topQRCodeVal = topQRCodeVal * 1920 / height;
                edgeQRCodeVal = edgeQRCodeVal * 1920 / height;
            }else if(SystemUtil.isTabletDevice(App.getContext())){ //平板部分适配
                height += SystemUtil.getDaoHangHeight(App.getContext());
                if("GEM-703L".equals(Build.MODEL)){
                    height += 210;
                }else if("SM-T230".equals(Build.MODEL)){
                    height += 80;
                }
                topTextVal = topTextVal * 1920 / height;
                topQRCodeVal = topQRCodeVal * 1920 / height;
                edgeQRCodeVal = edgeQRCodeVal * 1920 / height;
            }else { //手机适配
                if (height % 10 != 0) {
                    height += SystemUtil.getDaoHangHeight(App.getContext());
                }
                topTextVal = topTextVal * 1920 / height;
                topQRCodeVal = topQRCodeVal * 1920 / height;
                edgeQRCodeVal = edgeQRCodeVal * 1920 / height;
            }
        }

        int leftText = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, leftTextVal, getResources().getDisplayMetrics());
        int topText = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, topTextVal, getResources().getDisplayMetrics());
        int leftQRCode = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, leftQRCodeVal, getResources().getDisplayMetrics());
        int topQRCode = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, topQRCodeVal, getResources().getDisplayMetrics());
        int edgeQRCode = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, edgeQRCodeVal, getResources().getDisplayMetrics());

        String qrLink = "http://www.shadows.rocks/wxbrower/invite?link=";
        qrLink += mInviteInfo.url;
        Bitmap qrCodeBitmap = QRCodeUtils.createQRCodeBitmap(qrLink, edgeQRCode, edgeQRCode);
        Bitmap bgBitmap = ShareUtil.draw2Bitmap(App.getContext(), R.drawable.wx_share_bg_3);
        Bitmap textBitmap = ShareUtil.text2Bitmap(App.getContext(), wxShareContentTV);
        Bitmap meargeBitmapTemp = ShareUtil.mergeBitmapCustom(bgBitmap, textBitmap, leftText, topText);
        Bitmap mergeBitmap = ShareUtil.mergeBitmapCustom(meargeBitmapTemp, qrCodeBitmap, leftQRCode, topQRCode);
        String filePath = ShareUtil.saveBitmap(App.getContext(), mergeBitmap);
        ShareUtil.share2Wx(App.getContext(), filePath, isShareFriend);
    }

    @Override
    protected void onStop() {
        ProgressDialogUtil.hideProgress();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        wxShareContentTV.destroyDrawingCache();
        super.onDestroy();
    }
}